package cn.itcast.itcaststore.web.servlet;

import cn.itcast.itcaststore.domain.User;
import cn.itcast.itcaststore.service.Impl.IUserService;
import cn.itcast.itcaststore.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        UserService userService = new IUserService();
        User user=userService.getUser(username);

        request.setAttribute("username", username);
        request.setAttribute("password", password);
        //用户不存在
        if (user==null){

            request.setAttribute("register_message", "账户不存在，请注册！");
            request.getRequestDispatcher("/client/login.jsp").forward(request,response );

        }else if (user.getPassword().equals(password)){
            //成功登录

            request.getSession().setAttribute("login","true" );
            request.getSession().setAttribute("user",user);
            response.sendRedirect(request.getContextPath()+"/client/index.jsp");

        }else {

            //密码错误
            request.setAttribute("register_message","用户密码错误" );
            request.getRequestDispatcher("/client/login.jsp").forward(request,response );

        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
